package com.kaibes.module.permission;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.kaibes.core.base.util.IntegerUtils;
import com.kaibes.module.permission.db.service.PowerService;
import com.kaibes.module.user.UserService;
import com.kaibes.web.api.ApiLinkData;
import com.kaibes.web.api.ApiLinkService;
import com.kaibes.web.permission.PermissionChecker;

@Component
public class PermissionCheckerImpl implements PermissionChecker {

    @Autowired
    private UserService userService;
    @Autowired
    private PowerService powerService;
    @Autowired
    private ApiLinkService apiLinkService;
    
    private boolean hasPermission(Integer userId, Optional<ApiLinkData> optional) {
        // 接口没有注解权限
        if (!optional.isPresent()) {
            return true;
        }
        
        ApiLinkData apiLinkData = optional.get();
        // 接口权限无需登录
        if (!apiLinkData.isValidated()) {
            return true;
        }
        
        // 接口需要权限，但是没有登录
        if (IntegerUtils.isZero(userId)) {
            return false;
        }
        
        // 默认第一个用户为超级管理员，无需任何权限
        if (userId == 1) {
            return true;
        }
        
        // 剩下ApiLinkLevel.ADMIN需要判断权限
        // 判断是否拥有权限
        return powerService.countByRoleIdAndName(userService.getRoleIdById(userId), optional.get().getName()) > 0;
    }

    @Override
    public boolean hasPermission(Integer userId, String name) {
        return hasPermission(userId, apiLinkService.getByName(name));
    }

    @Override
    public boolean hasPermission(Integer userId, String uri, String method) {
        return hasPermission(userId, apiLinkService.getByUriAndMethod(uri, method));
    }

}
